package com.cy.demo.controller;

import com.cy.demo.controller.ex.*;
import com.cy.demo.pojo.User;
import com.cy.demo.service.IUserService;
import com.cy.demo.service.ex.InsertException;
import com.cy.demo.service.ex.UsernameDulicateException;
import com.cy.demo.utils.jsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
    @RequestMapping("users")
/*
*controller+response组合注解，表示当前类的所有方法返回为JSON格式
 */
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;


    @RequestMapping("reg")
    public jsonResult<Void> reg(User user){

            userService.reg(user);

       return new jsonResult<>(OK);
   }
    @RequestMapping("login")
   public jsonResult<User> login(String username , String password, HttpSession session){

        User data = new User();
        data=userService.login(username,password);
        //向session对象中完成数据的绑定
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //获取session中绑定的数据
//        System.err.println("uid==="+session.getAttribute("uid"));
//        System.err.println("username==="+session.getAttribute("username"));
        return new jsonResult<User>(data,OK);
   }
    @RequestMapping("change_password")
    public jsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){
        String username =  getUsernameFromSession(session);
        userService.updatePassword(username,oldPassword,newPassword);
        return new jsonResult<Void>(OK);
    }
    @RequestMapping("get_by_uid")
    public jsonResult<User> get_by_uid(HttpSession session){
        Integer uid = getuidFromSession(session);
        User data=userService.getByUid(uid);
        return new jsonResult<User>(data,OK);
    }
    @RequestMapping("change_info")
    public jsonResult<Void> change_info(HttpSession session,User user){
        Integer id = getuidFromSession(session);
        String phone = user.getPhone();
        String email = user.getEmail();
        Integer gender = user.getGender();
        userService.updateInfo(id,phone,email,gender);
        return new jsonResult<Void>(OK);
    }
    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE=10*1024*1024;

    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE=new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    /**
     * MultipartFile接口时SpringMVC提供的一个接口，这个接口为我们包装了
     * 获取文件类型的数据，Springboot它又整合了SpringMVC,只需要在处理请求
     * 的参数列表上声明一个参数类型为MultipartFile的参数，然后Springboot就自动
     * 将传递给服务器的文件数据赋值给这个参数
     * @param session
     * @param file
     * @return
     */
    @RequestMapping("change_avatar")
    public jsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file")  MultipartFile file) {
        //获取文件类型
        String contentType = file.getContentType();
        //判断文件是否为空
        if(file.isEmpty()){
            throw  new FileEmptyException("文件为空！");
        }else if(file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制！");
           // AVATAR_TYPE.contains(contentType)包含则返回true
        }else if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException();
        }
        //上传的文件的目录结构：.../upload/文件.png
        String parents = session.getServletContext().getRealPath("upload");
        //File对象指向这个路径，file是否存在
        File dir = new File(parents);
        if(!dir.exists()){//检测目录是否存在
            dir.mkdirs();//不存在将创建
        }
        //获取到这个文件名称，uuid工具类生成一个新的字符串作为文件名，防止文件名重复被覆盖
        String originalFIlename = file.getOriginalFilename();
        System.out.println("OriginalFilename="+originalFIlename);

        //获取文件的后缀
        int index = originalFIlename.lastIndexOf(".");
        String suffix=originalFIlename.substring(index);
        //处理后的文件名
        String filename=UUID.randomUUID().toString().toUpperCase()+suffix;
        //创建一个名称为filename的空文件
        File dest = new File(dir,filename);
        //将file文件的数据写入到空文件filename中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常！");
        }catch (FileStateException e){
            throw new FileStateException();
        }
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        //返回头像的路径
        String avatar = "/upload/"+filename;
        userService.updateAvatarByUid(uid,avatar,username);
        //返回用户的头像路径给前端页面，将来用于用户的头像展示使用
        return new jsonResult<String>(avatar,OK);
    }

    @RequestMapping("get_username")
    public jsonResult<String> getUsername(HttpSession session){
        String username = getUsernameFromSession(session);

        return new jsonResult<String>(username,OK);
    }
}
